<template>
	<view class="profile-page">
		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 姓名 -->
			<view class="form-item border" @click="ChooseImage">
				<text class="form-label">头像</text>
				<view class="form-label2">
					<image :src="userInfo.avatar || avatar" class="avatar" mode=""></image>
					<wd-icon name="arrow-right" color="#999999" size="16px"></wd-icon>
				</view>
			</view>
			<l-clipper v-if="show" :image-url="imageUrl" @success="imgSuccess" @cancel="show = false"  />
			<!-- 昵称 -->
			<view class="form-item" @click="toIntegral">
				<text class="form-label">积分</text>
				<view class="form-label2">
					<text class="form-value">{{surplusIntegral}}</text>
					<wd-icon name="arrow-right" color="#999999" size="13px"></wd-icon>
				</view>
			</view>
		</view>
		<!-- 表单区域 -->
		<view class="form-section" style="margin-top: 40rpx;">
			<view class="form-item">
				<text class="form-label">昵称</text>
				<view class="form-label2" v-if="!showInput" @click="showInput=!showInput">
					<text class="form-value">{{userInfo.nickname || ''}}</text>
					<wd-icon name="arrow-right" color="#999999" size="13px"></wd-icon>
				</view>
				<view class="form-label2" v-else>
					<wd-input type="text" no-border :focus="showInput" @blur="showInput=false" custom-class="custom-classInput" v-model.trim="userInfo.nickname" placeholder="请输入" @confirm="inputConfirm" />
				</view>
			</view>
			<view class="form-item" @click="show3=true">
				<text class="form-label">性别</text>
				<view class="form-label2" >
					<text class="form-value">{{userInfo.sex==1?'男':'女'}}</text>
					<wd-icon name="arrow-right" color="#999999" size="13px"></wd-icon>
				</view>
			</view>
			<wd-datetime-picker type="year" v-model="yearValue" @confirm="yearConfirm" :maxDate="Date.now()" :minDate="Date.now() - (31557600000*100)">
				<view class="form-item">
					<text class="form-label">年龄</text>
					<view class="form-label2">
						<text class="form-value">{{getYear || ''}}</text>
						<wd-icon name="arrow-right" color="#999999" size="13px"></wd-icon>
					</view>
				</view>
			</wd-datetime-picker>
			<wd-picker :columns="weightColumns" label="多列" v-model="weightValue" :column-change="onChangeDistrict" @confirm="weightConfirm">
				<view class="form-item">
					<text class="form-label">体重</text>
					<view class="form-label2">
						<text class="form-value">{{userInfo.weight?userInfo.weight:''}} <text v-if="userInfo.weight">{{userInfo.trainingUnit==1?'LB':'KG'}}</text> </text>
						<wd-icon name="arrow-right" color="#999999" size="13px"></wd-icon>
					</view>
				</view>
			</wd-picker>
		</view>
		<!-- 性别弹窗 -->
		<wd-action-sheet v-model="show3" cancel-text="取消" :actions="genderOptions" @close="show3=false" @select="GenderPicker" />
		<!-- 提交按钮 -->
		<view class="submit-section" @click="toLogout">
			退出登录
		</view>
	</view>
	<fui-loading type="col" v-if="loadActive" :isFixed="true" :isMask="true"></fui-loading>
</template>

<script setup>
	import { useUpload } from '@/uni_modules/wot-design-uni'
	import { useUserStore } from '@/store/user'
	import avatar from '@/static/imgnull.png'
	import lClipper from '@/pagesA/components/lime-clipper/components/l-clipper/l-clipper.vue'
	const userStore = useUserStore()
    const { startUpload, abort, chooseFile, UPLOAD_STATUS } = useUpload()
	const loadActive = ref(false);
	// 用户信息
	const userInfo = ref(userStore.userInfo);
	const surplusIntegral = ref(0);
	const showInput = ref(false);
	const show = ref(false);
	const show2 = ref(false);
	const show3 = ref(false);

	const yearValue = ref(Date.now() - (31557600000*18));
	const weightValue = ref(['40','KG']);
	const imageUrl = ref('false');
	
	const showAge = ref(false)
	const showWeight = ref(false)

	onLoad( () => {
		updateUserInfo();
		myIntegral();
	});
	// 计算属性获取年龄
	const getYear = computed(()=>{
		if(userInfo.value?.birthday){
			return uni.$uv.timeFrom2(userInfo.value.birthday,false);
		}
		return null
	})
	
	// 选择头像
	const ChooseImage = (e) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				imageUrl.value = res.tempFilePaths[0]
				show.value = true;
			}
		})
	}
	// 图片上传成功
	const imgSuccess = (e) => {
		// userInfo.avatar = e.detail.url
		console.log(e);
		// show.value = false;
		// 开始上传
		const file = {
		  url: e.url,
		  status: UPLOAD_STATUS.PENDING,
		  percent: 0
		}
		startUpload(file, {
		  action: `${getApp().globalData.baseUrl}/v4/user/setAvatar/4.0`,
		  formData:{
			  accessToken:userInfo.value.authenticationToken
		  },
		  onSuccess(res) {
			const data = JSON.parse(res.data);
			if(data.code==0){
				userInfo.value.avatar = data.data.avatar;
				updateUserInfo();
				uni.showToast({
					title: '修改成功',
					icon:'none'
				})
				show.value = false;
			}
		  },
		  onError(err) {
		    console.log('上传失败', err) 
		  },
		  onProgress(progress) {
		    console.log('上传进度', progress)
		  }
		})
	}
	// 积分记录
	const toIntegral = () => {
		uni.navigateTo({
			url: '/pagesA/view/integral/index',
		})
	}
	// 性别选项
	const genderOptions = ref([
		{ name: '女', value: '0' },
		{ name: '男', value: '1' },
	])

	// 体重选项 (30-150kg)
	const weightColumns = ref([
		  Array.from({ length: 110 }, (_, i) => (i + 40)) ,
		  ['KG', 'LB'],
	])
	
	const onChangeDistrict = (pickerView, value, columnIndex, resolve) => {
	  const item = value[columnIndex];
	  if(item.value=='KG'){
	  		pickerView.setColumnData(0, Array.from({ length: 110 }, (_, i) => (i + 40)))
	  }
	  if(item.value=='LB'){
		    pickerView.setColumnData(0, Array.from({ length: 240 }, (_, i) => (i + 88)))
	  }
	  resolve()
	}
	// 显示性别选择器
	const GenderPicker = (e) => {
		uni.api.updUserInfo({
			sex: e.index
		}).then(res => {
			userInfo.value.sex = e.index
			show3.value = false
			updateUserInfo();
			uni.showToast({
				title: '修改成功',
				icon:'none'
			})
		})
	}
	// 年龄选择器
	const yearConfirm = (e) => {
		uni.api.updUserBirth({
			birthday: uni.$uv.timeFormat(e.value,'yyyy-mm-dd hh:MM:ss')
		}).then(res => {
			userInfo.value.birthday = e.value
			updateUserInfo();
			uni.showToast({
				title: '修改成功',
				icon:'none'
			})
		})
	}
	
	
	// 显示性别选择器
	const weightConfirm = (e) => {
		uni.api.updUserInfo({
			weight:e.value[0],
			weightUnit:e.value[1]=="KG"?0:1,
		}).then(res => {
			console.log(userInfo.value);
			userInfo.value.weight = e.value[0];
			userInfo.value.trainingUnit = e.value[1]=="KG"?0:1;
			updateUserInfo();
			uni.showToast({
				title: '修改成功',
				icon:'none'
			})
		})
	}
	// 昵称修改
	const inputConfirm = () => {
		if(!userInfo.value.nickname){
			uni.showToast({
				title: '昵称不能为空',
				icon:'none'
			})
			return
		}
		uni.api.updUserInfo({
			nickname:userInfo.value.nickname,
		}).then(res => {
			updateUserInfo();
			uni.showToast({
				title: '修改成功',
				icon:'none'
			})
			// 让输入框失去焦点
			setTimeout(() => {
				showInput.value = false;
			}, 200);
			
		})
	}
	
	// 更新个人信息
	const updateUserInfo = () => {
		uni.api.userHome().then(res => {	
			userStore.login(res.data.authenticationToken,res.data);
		}).finally(()=>{
		})		
	}

	//获取积分
	const myIntegral = async () => {
		loadActive.value = true;
		const res = await uni.api.myIntegral();
		loadActive.value = false;
		if(res.code==0){
			surplusIntegral.value = res.data?.surplusIntegral || 0;
		}
	}

	// 退出登录
	const toLogout = ()=>{
		userStore.logout();
		uni.navigateBack({
			success:()=>{
				uni.showToast({
					title: '已退出',
					icon: 'none',
				});
			}
		})
	}
</script>

<style lang="scss">
	.profile-page {
		height: calc(100vh - 44px);
		background-color: #F5F5F5;
		padding: 40rpx 0;
	}

	.form-section {
		background-color: #fff;
		overflow: hidden;
		
		.border{
			border-bottom: 1px solid #F0F0F0;
		}
		.form-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 26rpx 30rpx;

			.form-label {
				font-size: 32rpx;
				color: #333;
				width: 120rpx;
				flex-shrink: 0;
			}
			.form-label2 {
				margin-left: auto;
				align-items: center;
				display: flex;
				.avatar {
					width: 143rpx;
					height: 143rpx;
					border-radius: 50%;
					margin-right: 10rpx;
				}
			}
		
			.form-input {
				flex: 1;
				font-size: 32rpx;
				color: #333;
				text-align: right;
				margin-right: 20rpx;

				.input-placeholder {
					color: #999;
				}
			}

			.form-value {
				flex: 1;
				font-size: 32rpx;
				color: #999;
				text-align: right;
				margin-right: 20rpx;
			}

			.form-arrow {
				font-size: 38rpx;
				color: #666666;
				font-weight: 300;
			}
		}
	}

	.submit-section {
		height: 89.06rpx;
		font-size: 31rpx;
		color: #333333;
		background-color: #fff;
		text-align: center;
		line-height: 89.06rpx;
		margin-top: 40rpx;
	}

	// 全局样式覆盖
	:deep(.wd-action-sheet__item) {
		font-size: 32rpx !important;
		color: #333 !important;
	}

	:deep(.wd-picker__toolbar) {
		background-color: #fff !important;
	}

	:deep(.wd-picker__confirm) {
		color: #333 !important;
	}

	:deep(.wd-picker__cancel) {
		color: #999 !important;
	}
	
</style>